package com.bhs.sansong.ui.dialog;

import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bhs.sansong.R;
import com.bhs.sansong.utils.EditTextUtil;
import com.bhs.sansong.utils.ToastUtil;
import com.lxj.xpopup.core.BottomPopupView;

import java.math.BigDecimal;

/**
 * 议价弹窗
 */
public class PriceInputDialog extends BottomPopupView implements View.OnClickListener {

    private EditText mEtPrice;
    private TextView mTvRangePrice;
    private Button mBtnConfirm;

    private BigDecimal price;

    public PriceInputDialog(@NonNull Context context, String price1) {
        super(context);
        price = new BigDecimal(price1);
    }

    @Override
    protected int getImplLayoutId() {
        return R.layout.dialog_price_input;
    }

    @Override
    protected void onCreate() {
        super.onCreate();
        mEtPrice = findViewById(R.id.et_price);
        mTvRangePrice = findViewById(R.id.tv_range_price);
        mBtnConfirm = findViewById(R.id.btn_confirm);
        mBtnConfirm.setOnClickListener(this);
        mEtPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                EditTextUtil.keepTwoDecimals(mEtPrice, 7);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                boolean verify = editable.length() > 0;
                mBtnConfirm.setEnabled(verify);
                mBtnConfirm.setBackgroundColor(verify ? Color.parseColor("#485EF4") : Color.parseColor("#7F485EF4"));

            }
        });
        mTvRangePrice.setText(String.format("议价范围(￥%s - ￥%s)", price.multiply(new BigDecimal("0.8")), price.multiply(new BigDecimal("1.2"))));
    }

    private MyClickListener2 listener;

    public void setMyClickListener(@Nullable MyClickListener2 l) {
        this.listener = l;
    }

    @Override
    public void onClick(View view) {
        String inputPrice = mEtPrice.getText().toString();
        if (price.multiply(new BigDecimal("0.8")).compareTo(new BigDecimal(inputPrice)) > -1
                && price.multiply(new BigDecimal("1.2")).compareTo(new BigDecimal(inputPrice)) < 1) {
            dismiss();
            listener.onClick("", mEtPrice.getText().toString());
        } else {
            ToastUtil.show("超出议价范围");
        }

    }
}
